import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Card,
  Button,
  message,
  Space,
  Form,
  Row,
  Col,
  Spin,
  DatePicker,
  Input,
  Radio,
  Popconfirm,
  Checkbox,
} from 'antd';
import { FormInstance } from 'antd/lib/form';
import { Map } from 'react-amap';
import classNames from 'classnames';
import styles from './style.less';
import { DeleteOutlined } from '@ant-design/icons';
import moment from 'moment';
import router from 'umi/router';

const InputSearch = Input.Search;
const options = [
  { label: '圆形', value: 1 },
  { label: '多边形', value: 2 },
];
const effectTypeOptions = [
  { label: '无限制', value: 0 },
  { label: '限制', value: 1 },
];
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 16 },
  },
};
const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  loading: state.loading.effects['electricFenceMng/postObj'],
});
class _customizeAdd extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      ins: null,
      record: null,
      isAdd: true,
      effectType: 0,
      searchKeyword: null,
      placeSearch: null,
      mouseTool: null,
      circleEditor: null,
      polyEditor: null,
      shape: null,
      display: true,
      spinning: true,
      isEdit: props.isEdit,
    };
  }

  open = () =>
    new Promise((resolve) => {
      const fenceId = this.props.location.query.fenceId;
      const { dispatch } = this.props;
      (fenceId
        ? dispatch({
            type: 'electricFenceMng/getData',
            payload: {
              url: '/electricfence/getfencedetail',
              fenceId,
            },
          })
        : Promise.resolve({})
      )
        .catch(() => ({}))
        .then((res) => {
          const record = res.data;
          this.setState(
            {
              record: record,
              display: true,
              isAdd: record ? false : true,
              effectType: record && record.fenceExpireDate ? 1 : 0,
              shape: record && record.fenceShapeType ? record.fenceShapeType : null,
            },
            () => {
              if (record) {
                this.formRef.current?.setFieldsValue({
                  fenceName: record.fenceName,
                  fenceShapeType: record.fenceShapeType,
                  effectType: record.fenceExpireDate ? 1 : 0,
                  fenceExpireDate: record.fenceExpireDate
                    ? moment(record.fenceExpireDate, 'YYYY-MM-DD  HH:mm:ss')
                    : null,
                });
              }
              // 标记数据加载完成
              resolve(true);
            },
          );
        });
    });

  close = () => {
    this.setState({ display: false }, () => {
      this.setState(
        {
          ins: null,
          record: null,
          effectType: 0,
          searchKeyword: null,
          placeSearch: null,
          mouseTool: null,
          circleEditor: null,
          polyEditor: null,
          shape: null,
          spinning: false,
        },
        () => {
          this.formRef.current?.resetFields();
          router.replace(`${self === top ? '' : '/external'}/electricFence/electricFenceMng`);
        },
      );
    });
  };

  drawCircleAndPolygon = () => {
    const { ins, shape, record } = this.state;
    //初始化圆形
    if (shape == 1 && record && record.radius && record.pointList && record.pointList.length > 0) {
      let circleIns = new AMap.Circle({
        map: ins,
        fillOpacity: 0.7,
        fillColor: '#4B9248',
        strokeStyle: 'solid',
        strokeColor: '#006633',
        radius: record.radius,
        center: [record.pointList[0].lng, record.pointList[0].lat],
      } as any);
      window.AMap.plugin('AMap.CircleEditor', () => {
        let circleEditorNew = new window.AMap.CircleEditor(ins, circleIns);
        circleEditorNew.open();
        this.setState({ circleEditor: circleEditorNew });
      });
      ins.setFitView();
    }
    //初始化多边形
    if (shape == 2 && record && record.pointList && record.pointList.length > 0) {
      let polygonPath: any = [];
      record.pointList.map((item: any) => {
        polygonPath.push(new AMap.LngLat(item.lng, item.lat));
      });
      let olygonIns = new AMap.Polygon({
        map: ins,
        fillOpacity: 0.7,
        fillColor: '#4B9248',
        strokeStyle: 'solid',
        strokeColor: '#006633',
        path: polygonPath,
        draggable: true,
      });
      window.AMap.plugin('AMap.PolyEditor', () => {
        let polyEditorNew = new window.AMap.PolyEditor(ins, olygonIns);
        polyEditorNew.open();
        this.setState({ polyEditor: polyEditorNew });
      });
      ins.setFitView();
    }
  };

  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onEffectTypeChange = (e: any) => {
    this.setState({ effectType: e.target.value });
  };

  onSearchSelect = (e: any) => {
    this.setState({ searchKeyword: e.poi.name });
    this.onSearchClick(e.poi.name);
  };

  onSearchInputChange = (e: any) => {
    this.setState({ searchKeyword: e.target.value });
  };

  onSearchClick = (value: any) => {
    const { placeSearch, ins, shape } = this.state;
    if (value && value.length > 0) {
      //关键字查询查询
      placeSearch.search(value, (status: any, result: any) => {
        if (status == 'error') {
          message.error(result);
          return;
        }
        if (status == 'no_data') {
          message.warning('根据地名未搜索到相关点信息');
          return;
        }
        if (status == 'complete' && result.info === 'OK') {
          ins.setCenter(result.poiList.pois[0].location);
          if (shape == 1) {
            let circle = ins.getAllOverlays('circle');
            if (circle && circle.length > 0) {
              circle[0].setCenter(result.poiList.pois[0].location);
            }
          }
          if (shape == 2) {
            let polygon = ins.getAllOverlays('polygon');
            if (polygon && polygon.length > 0) {
              let center = this.getCenterPoint(polygon[0].getPath());
              let newPath = this.calcNewPath(
                center,
                result.poiList.pois[0].location,
                polygon[0].getPath(),
              );
              polygon[0].setPath(newPath);
            }
          }
        } else {
          message.error('定位失败');
        }
      });
    }
  };

  onShapeChange = (e: any) => {
    const { ins, circleEditor, polyEditor } = this.state;
    let circle = ins.getAllOverlays('circle');
    let polygon = ins.getAllOverlays('polygon');
    this.setState({ shape: e.target.value });
    if (e.target.value == 1) {
      if (polygon && polygon.length > 0) {
        polygon[0].hide();
        polyEditor.close();
      }
      if (circle && circle.length > 0) {
        circle[0].show();
        circleEditor.open();
      } else {
        this.startDrawCircle();
      }
    }
    if (e.target.value == 2) {
      if (circle && circle.length > 0) {
        circle[0].hide();
        circleEditor.close();
      }
      if (polygon && polygon.length > 0) {
        polygon[0].show();
        polyEditor.open();
      } else {
        this.startDrawPolygon();
      }
    }
  };

  onClear = (type: any) => {
    const { ins, circleEditor, polyEditor } = this.state;
    if (type == 1) {
      let circle = ins.getAllOverlays('circle');
      if (circle && circle.length > 0) {
        ins.remove(circle);
        circleEditor.close();
        this.setState({ circleEditor: null }, () => {
          this.startDrawCircle();
        });
      }
    }
    if (type == 2) {
      let polygon = ins.getAllOverlays('polygon');
      if (polygon && polygon.length > 0) {
        ins.remove(polygon);
        polyEditor.close();
        this.setState({ polyEditor: null }, () => {
          this.startDrawPolygon();
        });
      }
    }
  };

  startDrawCircle = () => {
    const { mouseTool } = this.state;
    mouseTool.circle({
      fillOpacity: 0.7,
      fillColor: '#4B9248',
      strokeStyle: 'solid',
      strokeColor: '#006633',
    });
  };

  startDrawPolygon = () => {
    const { mouseTool } = this.state;
    mouseTool.polygon({
      fillOpacity: 0.7,
      fillColor: '#4B9248',
      strokeStyle: 'solid',
      strokeColor: '#006633',
    });
  };

  onDraw = (e: any) => {
    const { mouseTool, ins } = this.state;
    mouseTool.close(false);
    if (e.obj.CLASS_NAME == 'AMap.Circle') {
      let radius = e.obj.getRadius();
      e.obj.setRadius(Math.trunc(radius));
      window.AMap.plugin('AMap.CircleEditor', () => {
        let circleEditorNew = new window.AMap.CircleEditor(ins, e.obj);
        circleEditorNew.open();
        this.setState({ circleEditor: circleEditorNew });
      });
    }
    if (e.obj.CLASS_NAME == 'AMap.Polygon') {
      e.obj.setOptions({ draggable: true });
      window.AMap.plugin('AMap.PolyEditor', () => {
        let polyEditorNew = new window.AMap.PolyEditor(ins, e.obj);
        polyEditorNew.open();
        this.setState({ polyEditor: polyEditorNew });
      });
    }
  };

  getCenterPoint = (data: any) => {
    let lng = 0.0,
      lat = 0.0;
    for (let i = 0; i < data.length; i++) {
      lng = lng + parseFloat(data[i]['lng']);
      lat = lat + parseFloat(data[i]['lat']);
    }
    lng = lng / data.length;
    lat = lat / data.length;
    return { lng: Number(lng.toFixed(6)), lat: Number(lat.toFixed(6)) };
  };

  calcNewPath = (oldCenter: any, newCenter: any, path: any) => {
    let lngDiff = newCenter.lng - oldCenter.lng;
    let latDiff = newCenter.lat - oldCenter.lat;
    let newPath: any = [];
    path.map((item: any) => {
      let lng = item.lng + lngDiff;
      let lat = item.lat + latDiff;
      newPath.push([Number(lng.toFixed(6)), Number(lat.toFixed(6))]);
    });
    return newPath;
  };

  onFinish = (formValues: any) => {
    const { dispatch } = this.props;
    const { ins, shape, record } = this.state;
    const self = this;
    let param = { ...formValues };
    let latlng: any = null;
    //编辑时传围栏id
    if (record && record.fenceId != null) {
      param.fenceId = record.fenceId;
    }
    if (shape == 1) {
      let circle = ins.getAllOverlays('circle');
      if (circle && circle.length > 0) {
        latlng = circle[0].getCenter();
        param.radius = circle[0].getRadius();
        param.pointList = [
          {
            lat: latlng.lat,
            lng: latlng.lng,
          },
        ];
      } else {
        message.warning('请先绘制围栏');
        return;
      }
    }
    if (shape == 2) {
      let polygon = ins.getAllOverlays('polygon');
      if (polygon && polygon.length > 0) {
        let latlngCenter = this.getCenterPoint(polygon[0].getPath());
        let pointList: any = [];
        polygon[0].getPath().map((poi: any) => {
          pointList.push({
            lat: poi.lat,
            lng: poi.lng,
          });
        });
        param.pointList = pointList;
        latlng = [latlngCenter.lng, latlngCenter.lat];
      } else {
        message.warning('请先绘制围栏');
        return;
      }
    }
    window.AMap.plugin('AMap.Geocoder', () => {
      const geocoder = new window.AMap.Geocoder({});
      geocoder.getAddress(latlng, function (status: any, result: any) {
        if (status === 'complete' && result.regeocode) {
          param.fenceCenterDesc = result.regeocode.formattedAddress;
          if (formValues.effectType == 0) {
            param.fenceExpireDate = null;
          }
          if (formValues.effectType == 1) {
            param.fenceExpireDate =
              moment(formValues.fenceExpireDate).format('YYYY-MM-DD') + ' 23:59:59';
          }
          param.fenceType = 0;
          dispatch({
            type: 'electricFenceMng/postObj',
            payload: { url: '/electricfence/savefence', ...param },
            callback: (res: any) => {
              message.success('保存成功');
              self.close();
            },
          });
        } else {
          message.error('根据经纬度查询地址失败');
        }
      });
    });
  };

  render() {
    const { isAdd, effectType, searchKeyword, shape, ins, spinning, isEdit } = this.state;
    const { loading } = this.props;
    let isDrawCircle = false;
    let isDrawPolygn = false;
    if (ins) {
      let circle = ins.getAllOverlays('circle');
      if (circle && circle.length > 0) {
        isDrawCircle = true;
      }
      let polygon = ins.getAllOverlays('polygon');
      if (polygon && polygon.length > 0) {
        isDrawPolygn = true;
      }
    }
    const self = this;
    const mapEvent = {
      created: async (ins: any) => {
        // 地图创建好之后再加载数据
        await this.open();
        self.setState({ ins: ins, spinning: false }, () => {
          self.drawCircleAndPolygon();
        });
        window.AMap.plugin('AMap.MouseTool', () => {
          let mouseTool = new window.AMap.MouseTool(ins);
          (AMap.event.addListener as any)(mouseTool, 'draw', this.onDraw);
          self.setState({ mouseTool: mouseTool });
        });
        window.AMap.plugin('AMap.Autocomplete', () => {
          let auto = new window.AMap.Autocomplete({ input: 'autoinput' });
          (AMap.event.addListener as any)(auto, 'select', this.onSearchSelect);
        });
        window.AMap.plugin('AMap.PlaceSearch', () => {
          let placeSearch = new window.AMap.PlaceSearch({
            pageSize: 20,
          });
          self.setState({ placeSearch: placeSearch });
        });
        window.AMap.plugin('AMap.ToolBar', () => {
          let tool = new window.AMap.ToolBar({
            position: 'RB',
            ruler: false,
            locate: false,
            direction: false,
          });
          ins.addControl(tool);
        });
        window.AMap.plugin('AMap.Scale', () => {
          let scale = new window.AMap.Scale();
          ins.addControl(scale);
        });
      },
    };
    return (
      <Card
        title={isEdit ? (isAdd ? '新增围栏' : '编辑围栏') : '围栏详情'}
        onClose={this.close}
        bodyStyle={{ padding: '12px 24px' }}
        width={800}
        extra={
          <Space>
            <Button size="small" onClick={this.close}>
              取消
            </Button>
            （isEdit ?
            <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
              保存
            </Button>{' '}
            : '')
          </Space>
        }
      >
        <Spin spinning={spinning}>
          <Form style={{ marginTop: 12 }} ref={this.formRef} onFinish={this.onFinish}>
            <Row>
              <Col lg={12} md={12} sm={24} xs={24}>
                <FormItem
                  {...formItemLayout}
                  label="围栏所属组织"
                  name="xxxxxxx"
                  rules={[{ required: true, message: '请选择围栏所属组织' }]}
                >
                  <Input />
                </FormItem>
              </Col>
              <Col lg={12} md={12} sm={24} xs={24}>
                <FormItem {...formItemLayout} label="经销商" name="yyyyyyyyy">
                  <Input />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col lg={12} md={12} sm={24} xs={24}>
                <FormItem
                  {...formItemLayout}
                  label="围栏图形"
                  name="fenceShapeType"
                  rules={[{ required: true, message: '请选择围栏图形' }]}
                >
                  <Radio.Group
                    onChange={this.onShapeChange}
                    options={options}
                    optionType="button"
                    buttonStyle="solid"
                  />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col lg={12} md={12} sm={24} xs={24}>
                <FormItem
                  {...formItemLayout}
                  label="围栏预警方式"
                  name="warningType"
                  rules={[{ required: true, message: '请选择围栏预警方式' }]}
                >
                  <Checkbox.Group
                    options={[
                      { label: '进入围栏', value: '1' },
                      { label: '离开围栏', value: '2' },
                      { label: '围栏内', value: '3' },
                      { label: '围栏外', value: '4' },
                    ]}
                  />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col lg={12} md={12} sm={24} xs={24}>
                <FormItem
                  {...formItemLayout}
                  label="围栏有效期"
                  name="effectType"
                  rules={[{ required: true, message: '请选择围栏有效期' }]}
                  initialValue={0}
                >
                  <Radio.Group onChange={this.onEffectTypeChange} options={effectTypeOptions} />
                </FormItem>
              </Col>
              {effectType == 1 ? (
                <Col lg={12} md={12} sm={24} xs={24}>
                  <FormItem
                    {...formItemLayout}
                    label="限制日期"
                    name="fenceExpireDate"
                    rules={[{ required: true, message: '请选择限制日期' }]}
                  >
                    <DatePicker
                      placeholder="请选择限制日期"
                      style={{ width: '100%' }}
                      getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    />
                  </FormItem>
                </Col>
              ) : null}
            </Row>
          </Form>
          <div
            style={{
              height: 'calc(100vh - 320px)',
              border: '1px solid #d9d9d9',
              position: 'relative',
            }}
          >
            <div className={classNames(styles['searchDiv'])}>
              <InputSearch
                id={'autoinput'}
                allowClear
                autoComplete="off"
                placeholder="输入地名定位"
                value={searchKeyword}
                onChange={this.onSearchInputChange}
                onSearch={(value) => this.onSearchClick(value)}
                enterButton
                style={{ width: 200 }}
              />
            </div>
            {shape != null ? (
              <div className={classNames(styles['tipsDiv'])}>正在绘制围栏</div>
            ) : null}
            {shape == 1 && isDrawCircle ? (
              <div className={classNames(styles['clearDiv'])}>
                <Popconfirm
                  title="确定清除地图围栏？"
                  placement="left"
                  onConfirm={() => this.onClear(1)}
                >
                  <Button danger icon={<DeleteOutlined />} size="small">
                    清除
                  </Button>
                </Popconfirm>
              </div>
            ) : null}
            {shape == 2 && isDrawPolygn ? (
              <div className={classNames(styles['clearDiv'])}>
                <Popconfirm
                  title="确定清除地图围栏？"
                  placement="left"
                  onConfirm={() => this.onClear(2)}
                >
                  <Button danger icon={<DeleteOutlined />} size="small">
                    清除
                  </Button>
                </Popconfirm>
              </div>
            ) : null}
            {this.state.display ? (
              <Map ak={'19dbf6ffd63917bac5a923432ed8ca7a'} events={mapEvent} />
            ) : null}
          </div>
        </Spin>
      </Card>
    );
  }
}
export default connect(mapStateToProps)(_customizeAdd);
